package com.gxf.drugmg.controller;

import com.gxf.drugmg.entity.DrugRecognition;
import com.gxf.drugmg.service.DrugRecognitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/recognition")
@CrossOrigin(origins = "*")
public class DrugRecognitionController {
    
    @Autowired
    private DrugRecognitionService recognitionService;
    
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadAndRecognize(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要上传的图片文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                response.put("success", false);
                response.put("message", "请上传图片文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            DrugRecognition recognition = recognitionService.recognizeDrugs(file);
            
            response.put("success", true);
            response.put("message", "识别成功");
            response.put("data", recognition);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "识别失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    @GetMapping("/history")
    public ResponseEntity<List<DrugRecognition>> getRecognitionHistory() {
        List<DrugRecognition> recognitions = recognitionService.getAllRecognitions();
        return ResponseEntity.ok(recognitions);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<DrugRecognition> getRecognitionById(@PathVariable Long id) {
        DrugRecognition recognition = recognitionService.getRecognitionById(id);
        if (recognition != null) {
            return ResponseEntity.ok(recognition);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}